package com.luisliuyi.demo.optimize.network;

import android.text.TextUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Map;

import javax.net.ssl.SSLSocketFactory;

public class HttpConnection {
    private InputStream inputStream;
    private OutputStream outputStream;
    Socket socket;
    HttpUrl httpUrl;
    HttpCodec httpCodec = new HttpCodec();
    public void setHttpUrl(HttpUrl httpUrl) {
        this.httpUrl = httpUrl;
    }

    public boolean isSameAddress(String host, int port){
        if(null == socket){
            return false;
        }
        return TextUtils.equals(httpUrl.getHost(),host) && httpUrl.port == port;
    }

    private void createSocket() throws IOException {
        if (null == socket || socket.isClosed()) {
            if (httpUrl.protocol.equalsIgnoreCase("https")) {
                socket = SSLSocketFactory.getDefault().createSocket();
            } else {
                socket = new Socket();
            }
            socket.connect(new InetSocketAddress(httpUrl.getHost(), httpUrl.getPort()));
            inputStream = socket.getInputStream();
            outputStream = socket.getOutputStream();
        }
    }

    public void close(){
        if(null != socket){
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public String call(Request request) {
        try {
            createSocket();
        } catch (IOException e) {
            e.printStackTrace();
        }
        httpCodec.writeRequest(outputStream, request);
        return parseBody();
    }

    String statusLine;
    Map<String, String> headers;
    public boolean isKeepAlive( ){
        String[] status = statusLine.split(" ");
        boolean isKeepAlive = false;
        if(headers.containsKey("Connection")){
            isKeepAlive = headers.get("Connection").equalsIgnoreCase("Keep-Alive");
        }
        return isKeepAlive;
    }

    public String parseBody( )  {
        String body = null;
        try {
            statusLine =httpCodec.readLine(inputStream);
            //获取服务器返回的响应头
            headers = httpCodec.readHeaders(inputStream);
            int contentLength = -1;
            if(headers.containsKey("Content-Length")){
                contentLength = Integer.valueOf(headers.get("Content-Length"));
            }
            if(contentLength > 0){
                byte[] bodyBytes = httpCodec.readBytes(inputStream,contentLength);
                body = new String(bodyBytes,"UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return body ;
    }

}
